import { defineStore } from 'pinia'
import { useWebSocket } from '@vueuse/core'
import { onBeforeUnmount, watch } from 'vue'
import { EQUIPMENT_TYPE } from '@/utils/enums'


export const useDeviceData = defineStore('deviceData', {
  state: (): {
    deviceList: Record<string, unknown>[],
    statusList: Record<string, unknown>[]
  } => {
    return {
      deviceList: [],
      statusList: []
    }
  },
  getters: {
    //沉淀池
    precipitatePool: (state) => {
      return state.deviceList.filter(item => item.equipmentType === EQUIPMENT_TYPE.PRECIPITATE_POOL)
    },
    decayPool: (state) => {
      return state.deviceList.filter(item => item.equipmentType === EQUIPMENT_TYPE.DECAY_POOL)
    },
    waterPump: (state) => {
      return state.deviceList.filter(item => item.equipmentType === EQUIPMENT_TYPE.WATER_PUMP)
    },
    airProbe: (state) => {
      return state.deviceList.filter(item => item.equipmentType === EQUIPMENT_TYPE.AIR_PROBE)
    },
    valve: (state) => {
      return state.deviceList.filter(item => item.equipmentType === EQUIPMENT_TYPE.VALVE)
    }
  },
  actions: {
    linkWs: function(token: string) {
      console.log(token)
      const url = `ws://${window.location.host}${import.meta.env.VITE_BASE_API}/webSocket/${token}`
      const { data, close } = useWebSocket(url)
      watch(data, (newValue) => {
        const message: { data: any, type: number } = JSON.parse(newValue)
        if (message.type === 102) {
          this.deviceList = message.data as Record<string, unknown>[]
        } else if (message.type === 103) {
          this.statusList = message.data as Record<string, unknown>[]
        } else if (message.type === 104) {
          window.parent.postMessage({
            type: 'alarm',
            data: message.data
          }, '*')
        }
      })
      onBeforeUnmount(() => {
        close()
      })
    }
  }
})
